const { routerRedux } = dva.router;
import * as Request from '../utils/Request.jsx';
const AppUtils = require('../utils/AppUtils.jsx');
const StringUtils = require('../utils/StringUtils.jsx');

const { menus, username } = window.sys,
    collapsedStatus = 'index-collapsed';// 缓存菜单打开或关闭状态的key

export default {
    namespace: 'app',
    state: {
        loginSuccess: !!menus,
        collapsed: localStorage.getItem(collapsedStatus) === 'true',
        breadCrumbs: [],
        pathNames: [],
        menus: AppUtils.genMenu(menus || [], 0),// 生成菜单
        username: username
    },
    reducers: {
        toggle(state) {// 菜单打开关闭方法
            localStorage.setItem(collapsedStatus, !state.collapsed);// 记录打开或关闭状态
            return { ...state, collapsed: !state.collapsed }
        },
        setbreadCrumb(state, { payload: pathname }) {// 设置面包屑方法
            const pathNames = StringUtils.getUriPath(pathname);
            return { ...state, breadCrumbs: AppUtils.getbreadCrumb(pathNames), pathNames }
        },
        loginSuccess(state, { payload: { data } }) {// 登陆成功
            window.sys.id = data.id;// crsf token重新赋值(Request.jsx)
            window.sys.sns = new Set(data.sns);
            return {
                ...state,
                loginSuccess: true,
                menus: AppUtils.genMenu(data.menus || [], 0),// 生成菜单
                username: data.username,
                permissions: new Set(data.permissions || [])
            }
        },
        logoutSuccess(state) {
            return {  ...state, loginSuccess: false }
        }
    },
    effects: {
        *logout({ payload }, { call, put }) {// 退出登录
            const { data } = yield call(Request.post, 'logout');
            window.sys.id = data.id;// crsf token重新赋值(Request.jsx)
            yield put({ type: 'logoutSuccess' });
            yield put(routerRedux.push({ pathname: '/login' }));
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname, query }) => {
                if(pathname === 'index' && query['_p']) {// 用户直接访问url后台404返回处理
                    dispatch(routerRedux.push({ pathname: query['_p'] }));
                    return;
                }
                dispatch({ type: 'setbreadCrumb', payload: pathname });
            });
        },
    }
};